 /* 
  * Copyright (C) 2012 maxim 
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License as
  * published by the Free Software Foundation; either version 2 of the
  * License, or (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful, but
  * WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  * USA
  */

#include "tests.h"

#include "user_threads.h"
#include "user_mutex.h"

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

/* Create a chain of threads, until we can't create anymore
 * Then do a light test on zombies and vampires*/

static int thread1(void* arg)
{
	int given = *(int*)arg;
	assert(given == 10);


	int tid = uthread_create(thread1, (void*)(&given), 1);


	if (tid == UTHREAD_FAIL) {
		assert (uthread_self() == UTHREAD_MAX_THREADS -1);
		uthread_cancel(uthread_self());
		assert(0);
	}

	assert (tid == uthread_self() + 1);
	uthread_join(tid, NULL);
	return uthread_self();
}


void test4()
{
	msg("\nRunning test #4...");

	int arg = 10;
	assert(uthread_create(thread1, (void*)(&arg), 1) == 1);


	uthread_yield();
	uthread_cancel(1);

	int i;
	for (i = 1 ; i < UTHREAD_MAX_THREADS; i++)
		uthread_yield();

	/* Most of the threads should be gone now except thread 2 that is waited by zombie thread 1*/

	assert(uthread_join(1, &arg) == UTHREAD_SUCCESS);
	assert (arg == UTHREAD_CANCELLED);

	/* Now all threads should be gone */

	for (i = 1 ; i < UTHREAD_MAX_THREADS ; i++) {
		assert(uthread_join(i, &arg) == UTHREAD_INVALID);
	}
}
